package com.tengju.user.application.protocol;

import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.shared.ApplicationExceptionCode;
import com.tengju.user.domain.model.protocol.ProtocolType;
import com.tengju.user.domain.model.protocol.ProtocolVersion;
import com.tengju.user.domain.model.protocol.UserProtocol;
import com.tengju.user.domain.model.protocol.UserProtocolFactory;
import com.tengju.user.domain.model.user.UserInfo;
import com.tengju.user.domain.model.user.UserInfoRepository;
import com.tengju.user.domain.model.user.UserProtocolConfirmRepository;
import com.tengju.user.domain.shared.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserProtocolService {

    @Value("${user.protocol.version}")
    String protoVersions;

    private UserInfoRepository userInfoRepository;
    private UserProtocolConfirmRepository userProtocolConfirmRepository;

    @Autowired
    public UserProtocolService(UserInfoRepository userInfoRepository, UserProtocolConfirmRepository userProtocolConfirmRepository) {
        this.userInfoRepository = userInfoRepository;
        this.userProtocolConfirmRepository = userProtocolConfirmRepository;
    }

    public List<ProtocolVersion> getVersion(List<ProtocolType> types) {

        Map<String, Integer> versionMap = JsonUtil.toMap(protoVersions, new TypeReference<>() {});
        return types.stream().map(type -> {
            Integer version = Optional.ofNullable(versionMap).map(map -> map.get(type.name())).orElse(0);
            return new ProtocolVersion(type, version);
        }).collect(Collectors.toList());

    }


    public boolean confirmProtocol(UserInfo userInfo,List<ProtocolVersion> confirmVersions) {

        Map<ProtocolType, ProtocolVersion> currentVersionMap = userInfo.protocolInfoMap();

        for (ProtocolVersion  confirmVersion : confirmVersions) {
            ProtocolType protocolType = confirmVersion.getProtocolType();
            ProtocolVersion currentVersion = currentVersionMap.get(protocolType);

            if (currentVersion != null && currentVersion.compare(confirmVersion)>=0) {
                throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"确认版本小于等于用户当前版本");
            }

            UserProtocol userProtocol = UserProtocolFactory.createUserProtocol(userInfo, confirmVersion);
            userProtocolConfirmRepository.store(userProtocol);
            currentVersionMap.put(protocolType,confirmVersion);
        }


        userInfo.storeProtocolInfo(currentVersionMap);
        userInfoRepository.updateProtocolInfo(userInfo);


        return true;



    }
}
